<template>
  <div>
    <a-modal
      :title="isEdit ? (editLabel ? editLabel : addLabel) : addLabel"
      :visible="props.visible"
      @cancel="cancel"
      @beforeOk="beforeOk"
      @close="() => (isEdit = false)"
    >
      <a-form :model="form" ref="formRef">
        <template v-for="formItem in formList" :key="formItem.field">
          <a-form-item
            v-if="!isEdit || (isEdit && formItem.editshow)"
            :label="formItem.label"
            :field="formItem.field"
            :rules="formItem.rules"
            :validateTrigger="formItem.validateTrigger"
          >
            <template v-if="formItem.type === 'input'">
              <a-input
                v-model="form[formItem.field]"
                :placeholder="formItem.label"
                :disabled="!formItem.editable"
                allow-clear
              ></a-input>
            </template>
            <template v-else-if="formItem.type === 'textarea'">
              <a-textarea
                v-model="form[formItem.field]"
                :placeholder="formItem.label"
                allow-clear
                :auto-size="formItem.autoSize"
                :disabled="!formItem.editable"
              ></a-textarea>
            </template>
            <template v-else-if="formItem.type === 'select'">
              <a-select
                v-model="form[formItem.field]"
                :placeholder="formItem.label"
                :options="formItem.options"
                :multiple="formItem.multiple"
                :disabled="!formItem.editable"
                allow-clear
              ></a-select>
            </template>
            <template v-else-if="formItem.type === 'radio'">
              <a-radio-group
                v-model="form[formItem.field]"
                :options="formItem.options"
                :disabled="!formItem.editable"
              ></a-radio-group>
            </template>
            <template v-else-if="formItem.type === 'swicth'">
              <a-switch
                v-model="form[formItem.field]"
                :disabled="!formItem.editable"
              ></a-switch>
            </template>
            <template v-else-if="formItem.type === 'password'">
              <a-input-password
                :disabled="!formItem.editable"
                v-model="form[formItem.field]"
              ></a-input-password>
            </template>
            <template v-else>
              <slot
                :name="formItem.field"
                :record="formItem"
                :form="form"
              ></slot>
            </template>
            <template #help>
              <slot
                :name="`${formItem.field}_help`"
                :value="form[formItem.field]"
                :record="formItem"
              ></slot>
            </template>
          </a-form-item>
        </template>
      </a-form>
      <template #footer>
        <slot name="footer" :form="form"></slot>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import type { optionsFunc, optionsType } from "@/api";
import { Message, type FieldRule } from "@arco-design/web-vue";
import { ref, reactive } from "vue";
const formRef = ref();
interface Props {
  visible: boolean;
  formList: formItemType[];
  addLabel: string; //添加的时候，显示名字
  editLabel?: string; //编辑的时候，显示名字 没有就使用添加的
}

export interface formItemType {
  label: string;
  field: string;
  type?: "input" | "textarea" | "select" | "swicth" | "radio" | "password" | "";
  rules?: FieldRule<any> | FieldRule<any>[];
  source?: optionsType[] | optionsFunc;
  options?: optionsType[];
  validateTrigger?:
    | "focus"
    | "input"
    | "change"
    | "blur"
    | ("focus" | "input" | "change" | "blur")[];
  autoSize?:
    | boolean
    | {
        minRows?: number | undefined;
        maxRows?: number | undefined;
      };
  multiple?: boolean;
  editshow: boolean;
  editable?: boolean;
}
const props = defineProps<Props>();
const { addLabel, editLabel } = props;

const isEdit = ref<boolean>(false);
const emits = defineEmits<{
  cancel: [update_visible: boolean];
  create: [data: any, fn?: (val: boolean) => void];
  update: [data: any, fn?: (val: boolean) => void];
}>();

const formList = reactive<formItemType[]>([]);

const setForm = (formObj: any) => {
  isEdit.value = true;
  Object.assign(form, formObj);
};

defineExpose({ setForm });

const initFormList = async () => {
  for (const fItem of props.formList || []) {
    if (typeof fItem.source === "function") {
      try {
        const res = await fItem.source();
        fItem.options = res.data;
      } catch (e) {
        continue;
      }
    } else {
      fItem.options = fItem.source;
    }
    formList.push(fItem);
  }
};
initFormList();

const form = reactive<{ [key: string]: any }>({});
const cancel = () => {
  console.log("取消");

  formRef.value.clearValidate();
  formRef.value.resetFields();
  emits("cancel", false);
};

const beforeOk = async () => {
  const val = await formRef.value.validate();

  if (val) return false;
  console.log("表单校验通过", form);
  let close = true;
  //TODO 设置变量控制modal显影
  if (isEdit.value) {
    emits("update", form, (val: boolean) => {
      if (val === false) {
        close = false;
      }
    });
  } else {
    emits("create", form, (val: boolean) => {
      if (val === false) {
        close = false;
      }
    });
  }
  close ? cancel() : false;
};
</script>
<style scoped lang="less"></style>
